package st.shadow.library.core.base.mvp;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import st.shadow.library.core.base.fragment.BaseFragment;

/**
 * @author zhangyu
 * @date 2018/10/15
 */

public abstract class MvpFragment<T extends BasePresenter>
        extends BaseFragment {
    private View mTopView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mPresenter = getPresenter();
        if (mPresenter != null) {
            mPresenter.subscribe();
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.unSubscribe();
        }
    }

    protected void addTopView(int resourceId, ViewGroup group) {
        if (mTopView != null) {
            removeTopView(group);
        }
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        );
        mTopView = LayoutInflater.from(_mActivity).inflate(resourceId, null);
        group.addView(mTopView, group.getChildCount(), layoutParams);
    }

    protected void addTopView(int resourceId, ViewGroup group, int width, int height) {
        if (mTopView != null) {
            removeTopView(group);
        }
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                width, height
        );
        mTopView = LayoutInflater.from(_mActivity).inflate(resourceId, null);
        group.addView(mTopView, group.getChildCount(), layoutParams);
    }

    protected void removeTopView(ViewGroup group) {
        if (mTopView != null) {
            group.removeViewAt(group.getChildCount() - 1);
            mTopView = null;
        }
    }

    protected T mPresenter;

    abstract public T getPresenter();
}
